package initialize

import (
	"go.uber.org/zap"
	"gorm.io/gorm"
	"mycms/global"
	"mycms/model/system"
	"os"
)

const sys = "system"

func DBList() {
	dbMap := make(map[string]*gorm.DB)
	for _, info := range global.CONFIG.DBList {
		if info.Disable {
			continue
		}
		switch info.Type {
			case "mysql":
				dbMap[info.Dbname] = GormMysqlByConfig(info)
			default:
				continue
		}
	}
	// 做特殊判断,是否有迁移
	// 适配低版本迁移多数据库版本
	if sysDB, ok := dbMap[sys]; ok {
		global.DB = sysDB
	}
	global.DBList = dbMap
}

//	根据结构体自动生成数据库表
func RegisterTables(db *gorm.DB)  {

	engine := global.CONFIG.Mysql.Engine
	var err error

	//	TODO 键是表注释，值是数据表结构体
	models := map[string]interface{}{
		"管理员":     system.Admin{},
		"后台菜单":    system.Menu{},
		"后台角色":    system.Role{},
		"角色菜单关联表": system.RoleMenu{},
		"API管理表": system.Apis{},
		"菜单API关联表": system.MenuApis{},
	}


	if engine != "" && global.CONFIG.System.DbType == "mysql" {

		for k, v := range models{
			err = db.Set("gorm:table_options", "ENGINE="+engine+" COMMENT='"+k+"'").AutoMigrate(
				v,
			)

			if err != nil {
				global.LOG.Error("注册数据库表失败：", zap.Error(err))
				os.Exit(0)
			}
		}

	}else{
		for k, v := range models{
			err = db.Set("gorm:table_options", "COMMENT='"+k+"'").AutoMigrate(
				v,
			)

			if err != nil {
				global.LOG.Error("注册数据库表失败：", zap.Error(err))
				os.Exit(0)
			}
		}

	}


	global.LOG.Info("注册数据库表成功")
}
